<template>
  <div class="box cart">
    <header class="header">
      <van-nav-bar
        title="购物车"
        left-text="返回"
        right-text="去订单"
        left-arrow
        @click-left="onClickLeft"
        @click-right="$router.push('/order')"
      />
    </header>
    <div class="content">
      <van-empty description="购物车里空空如也" v-if="!cartList.length">
        <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">
          去购物吧
        </van-button>
      </van-empty>
      <div v-else>
        <van-swipe-cell v-for="(val,idx) in cartList" :key="val.proId">
          <van-card
            :price="val.price"
            :title="val.proName"
            :desc="val.time"
            class="goods-card"
          >
            <template #num>
              <van-stepper v-model="val.num" theme="round" button-size="22" max="999" @change="change" :name="val.proId" />
            </template>
            <template #thumb>
              <van-checkbox v-model="val.flag" @click="oneFlag(idx)"></van-checkbox>
              <van-image :src="val.proImg" fit="cover" />
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="del(val.proId,idx)" />
          </template>
        </van-swipe-cell>
        <van-submit-bar :price="priceSum*100" button-text="提交订单" @submit="onSubmit">
          <van-checkbox v-model="allChecked" @click="allFlag">全选</van-checkbox>
          <template #tip>
            当前商品总共： <span>{{numSum}}</span> 件
          </template>
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { SwipeCell, Card, Empty, SubmitBar, Checkbox, Image as VanImage, Stepper, Dialog, NavBar, Button } from 'vant'
import { getCart, getDetail, updateCartNum, updateCartFlag, updateCartFlagAll, deleteCart } from '../../api/index.js'

Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(Empty)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(VanImage)
Vue.use(Stepper)
Vue.use(Dialog)
Vue.use(NavBar)
Vue.use(Button)

export default {
  data () {
    return {
      cartList: []
    }
  },
  computed: {
    allChecked: {
      get () {
        return this.cartList.every(val => {
          return val.flag
        })
      },
      set (v) {
        for (let i = 0; i < this.cartList.length; i++) {
          this.cartList[i].flag = v
        }
      }
    },
    numSum () {
      var a = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].flag) {
          a += this.cartList[i].num
        }
      }
      return a
    },
    priceSum () {
      var a = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].flag) {
          a += this.cartList[i].num * this.cartList[i].price
        }
      }
      return a
    }
  },
  mounted () {
    getCart({
      userId: localStorage.getItem('userId')
    }).then(res => {
      console.log(1)
      console.log(res)
      if (res.data.state === 200) {
        const arr = res.data.data[0].cartData
        arr.forEach(val => {
          getDetail({ proId: val.proId }).then(data => {
            const obj = data.data.data[0]
            obj.num = val.num
            obj.time = val.time + ''
            obj.flag = val.flag
            this.cartList.push(obj)
          })
        })
        console.log(this.cartList)
        this.cartList.sort((a, b) => {
          return a.time - b.time
        })
      }
    })
  },
  // 组件路由守卫
  beforeRouteEnter (to, from, next) {
    if (localStorage.getItem('isLogin') === 'ok') {
      next()
    } else {
      next('/login?t=' + to.path)
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    onSubmit () {
      let arr = []
      arr = this.cartList.filter(val => {
        return val.flag
      })
      console.log(arr)
      // addOrder({
      //   userId: localStorage.getItem('userId'),
      //   proData: arr
      // }).then(res => {
      //   console.log(res.data)
      // })
      this.$router.push('/orderPay')
    },
    change (value, detail) {
      console.log(1)
      updateCartNum({
        userId: localStorage.getItem('userId'),
        proId: detail.name,
        num: value
      }).then(res => {
        console.log(1)
      })
    },
    oneFlag (idx) {
      updateCartFlag({
        userId: localStorage.getItem('userId'),
        proId: this.cartList[idx].proId,
        flag: this.cartList[idx].flag
      }).then(res => {
        console.log(res.data)
      })
    },
    allFlag () {
      updateCartFlagAll({
        userId: localStorage.getItem('userId'),
        flag: this.allChecked
      }).then(res => {
        console.log(res.data)
      })
    },
    del (proId, idx) {
      Dialog.confirm({
        title: '标题',
        message: '弹窗内容'
      }).then(() => {
        deleteCart({
          userId: localStorage.getItem('userId'),
          proId: proId
        }).then(res => {
          this.cartList.splice(idx, 1)
        })
      }).catch(() => {
        console.log('失败')
      })
    }
  }
}
</script>

<style lang="scss">
  .cart{
    .delete-button {
      height: 100%;
    }
    .van-card__thumb {
      display: flex;
      width: 1.2rem;
      img {
        width: 0.88rem;
      }
    }
  }
</style>
